<template>
  <div class="goods-publish-form">
    <el-form
      ref="goodsForm"
      :model="goodsForm"
      :rules="rules"
      label-width="120px"
      class="publish-form"
    >
      <!-- 商品基本信息 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>商品基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input
                v-model="goodsForm.goodsName"
                placeholder="请输入商品名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="categoryId">
              <el-select
                v-model="goodsForm.categoryId"
                placeholder="请选择商品分类"
                style="width: 100%"
                :loading="categoryLoading"
              >
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.categoryName"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="goodsForm.price"
                :min="0"
                :precision="2"
                :step="0.01"
                style="width: 100%"
                placeholder="请输入商品价格"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品原价" prop="originalPrice">
              <el-input-number
                v-model="goodsForm.originalPrice"
                :min="0"
                :precision="2"
                :step="0.01"
                style="width: 100%"
                placeholder="请输入商品原价"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="goodsForm.stock"
            :min="1"
            :precision="0"
            style="width: 100%"
            placeholder="请输入库存数量"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="goodsForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述商品信息，包括成色、使用情况等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="商品标签" prop="tags">
          <el-select
            v-model="goodsForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入商品标签（可选）"
            style="width: 100%"
          >
            <el-option label="新品" value="新品" />
            <el-option label="热销" value="热销" />
            <el-option label="推荐" value="推荐" />
            <el-option label="限时" value="限时" />
            <el-option label="包邮" value="包邮" />
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 商品图片 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>商品图片</span>
          </div>
        </template>
        
        <el-form-item label="商品主图" prop="mainImage">
          <el-upload
            ref="mainImageUpload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleMainImageRemove"
            :on-success="handleMainImageSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeMainImageUpload"
            :file-list="mainImageList"
            list-type="picture-card"
            :limit="1"
            accept="image/*"
            name="files"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="upload-tip">请上传商品主图（必填）</div>
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            ref="upload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeImageUpload"
            :file-list="fileList"
            list-type="picture-card"
            :limit="6"
            accept="image/*"
            name="files"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="upload-tip">可上传多张商品图片（可选）</div>
          
          <el-dialog :visible.sync="dialogVisible" title="图片预览">
            <img style="width: 100%" :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-card>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          发布商品
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import axios from '@/utils/axios'

export default {
  name: 'GoodsPublishForm',
  data() {
    return {
      goodsForm: {
        goodsName: '',
        categoryId: null,
        price: null,
        originalPrice: null,
        stock: 1,
        description: '',
        mainImage: '',
        images: [],
        tags: []
      },
      rules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
        ],
        originalPrice: [
          { required: true, message: '请输入商品原价', trigger: 'blur' },
          { type: 'number', min: 0, message: '原价必须大于0', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
          { type: 'number', min: 1, message: '库存必须大于0', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入商品描述', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ]
      },
      fileList: [],
      mainImageList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      submitting: false,
      uploadUrl: 'http://localhost:8079/admin/product/multiUpload', // 多图上传接口
      categoryList: [], // 分类列表
      categoryLoading: false // 分类加载状态
    }
  },
  computed: {
    uploadHeaders() {
      return {
        'Authorization': `Bearer ${this.$store.state.user.token}`
      }
    }
  },
  mounted() {
    // 组件挂载时获取分类列表
    this.getCategoryList()
  },
  methods: {
    // 获取分类列表
    async getCategoryList() {
      try {
        this.categoryLoading = true
        const response = await axios.get('/category/list')
        if (response.data.success) {
          this.categoryList = response.data.data
        } else {
          this.$message.error('获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      } finally {
        this.categoryLoading = false
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        // 验证表单
        await this.$refs.goodsForm.validate()
        
        // 验证主图是否上传
        if (this.mainImageList.length === 0) {
          this.$message.error('请上传商品主图')
          return
        }
        
        this.submitting = true
        
        // 获取当前用户ID
        const userInfo = JSON.parse(localStorage.getItem('user') || '{}')
        const userId = userInfo.userId || this.$store.state.user.userId
        
        if (!userId) {
          this.$message.error('用户信息获取失败，请重新登录')
          return
        }
        
        // 准备表单数据
        const formData = {
          userId: userId.toString(),
          userName: userInfo.username || this.$store.state.user.username,
          goodsName: this.goodsForm.goodsName,
          description: this.goodsForm.description,
          price: this.goodsForm.price,
          originalPrice: this.goodsForm.originalPrice,
          stock: this.goodsForm.stock,
          categoryId: this.goodsForm.categoryId,
          mainImage: this.mainImageList.length > 0 ? this.mainImageList[0].url : ''
        }
        
        // 添加可选参数
        
        if (this.fileList.length > 0) {
          formData.images = JSON.stringify(this.fileList.map(file => file.url))
        }
        
        if (this.goodsForm.tags.length > 0) {
          formData.tags = JSON.stringify(this.goodsForm.tags)
        }
        
        // 发送请求
        const response = await axios.post('/goods/add', formData)
        
        if (response.data.success) {
          this.$message.success('商品发布成功！')
          this.$emit('publish-success')
          this.resetForm()
        } else {
          this.$message.error(response.data.message || '发布失败')
        }
      } catch (error) {
        console.error('发布商品失败:', error)
        this.$message.error('发布失败，请重试')
      } finally {
        this.submitting = false
      }
    },
    
    // 重置表单
    resetForm() {
      this.$refs.goodsForm.resetFields()
      this.fileList = []
      this.mainImageList = []
    },
    
    // 主图上传成功
    handleMainImageSuccess(response, file, fileList) {
      console.log('主图上传成功:', response)
      if (response.code === 200 && response.data && response.data.length > 0) {
        // 后端返回的是URL数组，取第一个作为主图URL
        file.url = response.data[0]
        this.mainImageList = fileList
        this.$message.success('主图上传成功')
      } else {
        this.$message.error(response.message || '主图上传失败')
        // 从文件列表中移除失败的文件
        this.mainImageList = fileList.filter(item => item.uid !== file.uid)
      }
    },
    
    // 删除主图
    handleMainImageRemove(file, fileList) {
      this.mainImageList = fileList
    },
    
    // 图片上传成功
    handleUploadSuccess(response, file, fileList) {
      console.log('图片上传成功:', response)
      if (response.code === 200 && response.data && response.data.length > 0) {
        // 后端返回的是URL数组，取第一个作为当前图片URL
        file.url = response.data[0]
        this.fileList = fileList
        this.$message.success('图片上传成功')
      } else {
        this.$message.error(response.message || '图片上传失败')
        // 从文件列表中移除失败的文件
        this.fileList = fileList.filter(item => item.uid !== file.uid)
      }
    },
    
    // 图片上传失败
    handleUploadError(error, file, fileList) {
      console.error('图片上传失败:', error)
      this.$message.error('图片上传失败，请重试')
      // 从文件列表中移除失败的文件
      this.fileList = fileList.filter(item => item.uid !== file.uid)
    },
    
    // 删除图片
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    
    // 主图上传前验证
    beforeMainImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$message.error('主图只能是图片格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('主图大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    // 图片上传前验证
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      
      if (!isImage) {
        this.$message.error('只能上传图片格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
  }
}
</script>

<style scoped>
.goods-publish-form {
  max-width: 100%;
  margin: 0 auto;
}

.publish-form {
  background-color: transparent;
}

.form-card {
  margin-bottom: 30px;
  border: none;
  box-shadow: 0px 2px 10px 1px #0000002a;
  border-radius: 20px;
  overflow: hidden;
}

.form-card:last-child {
  margin-bottom: 0;
}

.card-header {
  font-weight: 600;
  color: #00caa8;
  font-size: 18px;
  padding: 20px 0;
}

.form-actions {
  text-align: center;
  padding: 30px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

.form-actions .el-button {
  margin: 0 15px;
  padding: 12px 40px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 500;
}

.form-actions .el-button--primary {
  background-color: #00caa8;
  border-color: #00caa8;
}

.form-actions .el-button--primary:hover {
  background-color: #00b894;
  border-color: #00b894;
}

/deep/ .el-upload--picture-card {
  border-color: #00caa8;
  border-radius: 10px;
}

/deep/ .el-upload--picture-card:hover {
  border-color: #00b894;
}

/deep/ .el-form-item__label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

/deep/ .el-input__inner:focus,
/deep/ .el-textarea__inner:focus {
  border-color: #00caa8;
  border-radius: 8px;
}

/deep/ .el-select .el-input.is-focus .el-input__inner {
  border-color: #00caa8;
  border-radius: 8px;
}

/deep/ .el-input__inner,
/deep/ .el-textarea__inner,
/deep/ .el-select .el-input__inner {
  border-radius: 8px;
}

/deep/ .el-input-number .el-input__inner {
  border-radius: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}

/deep/ .el-card__header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 20px 30px;
}

/deep/ .el-card__body {
  padding: 30px;
}

/deep/ .el-form-item {
  margin-bottom: 25px;
}

/deep/ .el-row {
  margin-bottom: 0;
}
</style> 